home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Freeware / Griffith 0.9.8 / griffith-0.9.8-win32.exe / {app} / lib / plugins / imp / __init__.py next >
Text File  |  2008-11-17  |  8KB  |  239 lines

  1. # -*- coding: UTF-8 -*-
  2.  
  3. __revision__ = '$Id: __init__.py 1040 2008-11-15 21:13:49Z mikej06 $'
  4.  
  5. # Copyright (c) 2006-2007 Piotr O┼╝arowski
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published byp
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15. # GNU Library General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program; if not, write to the Free Software
  19. # 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
  20.  
  21. # You may use and distribute this software under the terms of the
  22. # GNU General Public License, version 2 or later
  23.  
  24. # detect all plugins:
  25. import glob, os.path
  26.  
  27. __all__ = [os.path.basename(x)[:-3] for x in glob.glob("%s/*.py" % os.path.dirname(__file__))]
  28. __all__.remove('__init__')
  29.  
  30. class ImportPlugin:
  31.     description = None
  32.     author = None
  33.     email = None
  34.     version = None
  35.     # file chooser:
  36.     file_filters = None
  37.     mime_types = None
  38.  
  39.     edit = False        # open add window for every movie?
  40.  
  41.     imported = 0
  42.     data = None
  43.  
  44.     def __init__(self, parent, fields_to_import):
  45.         self.db        = parent.db
  46.         self.debug    = parent.debug
  47.         self.locations    = parent.locations
  48.         self.fields    = parent.field_names
  49.         self.conditions    = parent._conditions
  50.         self.colors    = parent._colors
  51.         self.lang_types    = parent._lang_types
  52.         self.layers    = parent._layers
  53.         self.regions    = parent._regions
  54.         self.widgets    = parent.widgets['import']
  55.         self.fields_to_import = fields_to_import
  56.         self._abort    = False
  57.  
  58.     def initialize(self):
  59.         """Initializes plugin (get all parameters from user, etc.)"""
  60.         self.imported = 0
  61.         return True
  62.  
  63.     def abort(self, *args):
  64.         """called after abort button clicked"""
  65.         self._abort = True
  66.  
  67.     def set_source(self, name):
  68.         """Prepare source (open file, etc.)"""
  69.  
  70.     def count_movies(self):
  71.         """Returns number of movies in file which is about to be imported"""
  72.         pass
  73.  
  74.     def get_movie_details(self):
  75.         """Returns dictionary with movie details"""
  76.         pass
  77.  
  78.     def run(self, name):
  79.         """Import movies, function called in a loop over source files"""
  80.         from add import validate_details, edit_movie
  81.         from gutils import find_next_available
  82.         from sqlalchemy import Select, func
  83.         import gtk
  84.         
  85.         if not self.set_source(name):
  86.             self.debug.show("Can't read data from file %s" % name)
  87.             return False
  88.         
  89.         self.widgets['pwindow'].show()
  90.         while gtk.events_pending():    # give GTK some time for updates
  91.             gtk.main_iteration()
  92.  
  93.         # progressbar
  94.         update_on = []
  95.         count = self.count_movies()
  96.         if count > 0:
  97.             for i in range(0,100):
  98.                 update_on.append(int(float(i)/100*count))
  99.  
  100.         statement = Select( [ func.max(self.db.Movie.c.number) ] )
  101.         number = statement.execute().fetchone()[0]
  102.         if number is None:
  103.             number = 1
  104.         else:
  105.             number += 1
  106.  
  107.         statement = Select([self.db.Movie.c.number])
  108.  
  109.         processed = 0
  110.         while self._abort is False:
  111.             details = self.get_movie_details()
  112.             if details is None:
  113.                 break
  114.  
  115.             processed += 1
  116.             if processed in update_on:
  117.                 self.widgets['progressbar'].set_fraction(float(processed)/float(count))
  118.                 gtk.main_iteration()
  119.                 self.widgets['progressbar'].set_text("%s (%s/%s)" % (str(self.imported), str(processed), str(count)))
  120.                 gtk.main_iteration()
  121.                 gtk.main_iteration() # extra iteration for abort button
  122.  
  123.             if (details.has_key('o_title') and details['o_title']) or (details.has_key('title') and details['title']):
  124.                 if details.has_key('o_title') and details['o_title']:
  125.                     statement.whereclause = func.lower(self.db.Movie.c.o_title)==details['o_title'].lower()
  126.                     if details.has_key('title') and details['title']:
  127.                         statement.append_whereclause( func.lower(self.db.Movie.c.title)==details['title'].lower() )
  128.                     tmp = statement.execute().fetchone()
  129.                     if tmp is not None:
  130.                         self.debug.show("movie already exists (number=%s, o_title=%s)" % (tmp.number, details['o_title']))
  131.                         continue
  132.                 elif details.has_key('title') and details['title']:
  133.                     statement.whereclause = func.lower(self.db.Movie.c.title)==details['title'].lower()
  134.                     tmp = statement.execute().fetchone()
  135.                     if tmp is not None:
  136.                         self.debug.show("movie already exists (number=%s, title=%s)" % (tmp.number, details['title']))
  137.                         continue
  138.                 validate_details(details, self.fields_to_import)
  139.                 if self.edit is True:
  140.                     response = edit_movie(self.parent, details)    # FIXME: wait until save or cancel button pressed
  141.                     if response == 1:
  142.                         self.imported += 1
  143.                 else:
  144.                     if not details.has_key('number') or (details.has_key('number') and details['number'] is None):
  145.                         #details['number'] = find_next_available(self.db)
  146.                         details['number'] = number
  147.                         number += 1
  148.                     #movie = self.db.Movie()
  149.                     #movie.add_to_db(details)
  150.                     try:
  151.                         self.db.Movie.mapper.mapped_table.insert().execute(details)
  152.                         self.imported += 1
  153.                     except Exception, e:
  154.                         self.debug.show("movie details are not unique, skipping: %s" % str(e))
  155.             else:
  156.                 self.debug.show('skipping movie without title or original title')
  157.         self.widgets['pwindow'].hide()
  158.         return True
  159.  
  160.     def clear(self):
  161.         """clear plugin before next source file"""
  162.         self.data = None
  163.         self.imported = 0
  164.         self.__source_name = None
  165.         self._abort = False
  166.     
  167.     def destroy(self):
  168.         """close all resources"""
  169.         pass
  170.  
  171.  
  172. def on_import_plugin_changed(combobox, widgets, *args):
  173.     from gtk import FileFilter
  174.     import plugins.imp
  175.     plugin_name = widgets['plugin'].get_active_text()
  176.     __import__("plugins.imp.%s" % plugin_name)
  177.     ip = eval("plugins.imp.%s.ImportPlugin" % plugin_name)
  178.     widgets['author'].set_markup("<i>%s</i>" % ip.author)
  179.     widgets['email'].set_markup("<i>%s</i>" % ip.email)
  180.     widgets['version'].set_markup("<i>%s</i>" %ip.version)
  181.     widgets['description'].set_markup("<i>%s</i>" %ip.description)
  182.     # file filters
  183.     for i in widgets['fcw'].list_filters():
  184.         widgets['fcw'].remove_filter(i)
  185.     f = FileFilter()
  186.     f.set_name(plugin_name)
  187.     if ip.file_filters is not None:
  188.         if isinstance(ip.file_filters, tuple) or isinstance(ip.file_filters, list):
  189.             for i in ip.file_filters:
  190.                 f.add_pattern(i)
  191.         else:
  192.             f.add_pattern(ip.file_filters)
  193.     if ip.mime_types is not None:
  194.         if isinstance(ip.mime_types, tuple) or isinstance(ip.mime_types, list):
  195.             for i in ip.mime_types:
  196.                 f.add_mime_type(i)
  197.         else:
  198.             f.add_mime_type(ip.mime_types)
  199.     widgets['fcw'].add_filter(f)
  200.     f = FileFilter()
  201.     f.set_name(_("All files"))
  202.     f.add_pattern("*")
  203.     widgets['fcw'].add_filter(f)
  204.  
  205. def on_import_button_clicked(button, self, *args):
  206.     import plugins.imp, gutils
  207.     plugin_name = self.widgets['import']['plugin'].get_active_text()
  208.     filenames = self.widgets['import']['fcw'].get_filenames()
  209.     
  210.     fields = []
  211.     w = self.widgets['import']['fields']
  212.     for i in w:
  213.         if w[i].get_active():
  214.             fields.append(i)
  215.  
  216.     __import__("plugins.imp.%s" % plugin_name)
  217.     ip = eval("plugins.imp.%s.ImportPlugin(self, fields)" % plugin_name)
  218.     if ip.initialize():
  219.         self.widgets['window'].set_sensitive(False)
  220.         self.widgets['import']['window'].hide()
  221.         self.widgets['import']['pabort'].connect('clicked', ip.abort, ip)
  222.         for filename in filenames:
  223.             self.widgets['import']['progressbar'].set_fraction(0)
  224.             self.widgets['import']['progressbar'].set_text('')
  225.             if ip.run(filename):
  226.                 gutils.info(self, _("%s file has been imported. %s movies added.") \
  227.                     % (plugin_name, ip.imported), self.widgets['window'])
  228.                 self.populate_treeview()
  229.             ip.clear()
  230.         ip.destroy()
  231.         self.widgets['import']['pwindow'].hide()
  232.         self.widgets['window'].set_sensitive(True)
  233.  
  234. def on_abort_button_clicked(button, self, *args):
  235.     self.widgets['import']['window'].hide()
  236.     self.widgets['import']['pwindow'].hide()
  237.     self.widgets['window'].set_sensitive(True)
  238.  
  239.